package com.ruoyi.marketing.service.impl;

import java.util.Date;
import java.util.List;

import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.marketing.domain.AwardDetail;
import com.ruoyi.marketing.domain.AwardPerson;
import com.ruoyi.marketing.domain.MarketingTask;
import com.ruoyi.marketing.service.IAwardDetailService;
import com.ruoyi.marketing.service.IAwardPersonService;
import com.ruoyi.marketing.utils.PrizeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.marketing.mapper.MarketingAwardMapper;
import com.ruoyi.marketing.domain.MarketingAward;
import com.ruoyi.marketing.service.IMarketingAwardService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 营销奖励Service业务层处理
 *
 * @author hao
 * @date 2023-01-30
 */
@Service
public class MarketingAwardServiceImpl extends ServiceImpl<MarketingAwardMapper, MarketingAward> implements IMarketingAwardService {
    @Autowired
    private IAwardDetailService awardDetailService;
    @Autowired
    private IAwardPersonService awardPersonService;

    /**
     * 查询营销奖励列表
     *
     * @param marketingAward 营销奖励
     * @return 营销奖励
     */
    @Override
    public List<MarketingAward> selectMarketingAwardList(MarketingAward marketingAward) {
        return getBaseMapper().selectMarketingAwardList(marketingAward);
    }


    @Transactional(rollbackFor = Exception.class)
    @Override
    public MarketingAward getAward(String marketId) {
        // 1. 判断当前用户是否有抽奖次数
        AwardPerson visitUser = awardPersonService.getByUserId(SecurityUtils.getUserId(), marketId);
        if (visitUser.getPrizeNum() < 0) {
            throw new ServiceException("你没有抽奖次数!请完成任务获取抽奖次数.");
        }
        MarketingAward gift = PrizeUtils.gift(marketId);
        visitUser.setPrizeNum(visitUser.getPrizeNum() - 1);
        awardPersonService.updateChoujTimes(visitUser);
        if (gift == null) {
            throw new ServiceException("谢谢参与");
        }
        visitUser.setDrawNum(visitUser.getDrawNum() + 1);
        awardPersonService.updateZhongjTimes(visitUser);
        AwardDetail detail = new AwardDetail();
        detail.setUserId(SecurityUtils.getUserId());
        detail.setAwardId(marketId);
        detail.setTaskId(3L);
        detail.setAwardTime(new Date());
        detail.setAwardId(gift.getAwardId()+"");
        awardDetailService.save(detail);
        return gift;
    }
}
